package com.strawberry.chat2.library.netease.p2p;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.strawberry.chat2.MyReactDelegate;

import java.util.List;

public class Util {
    public static ReactApplicationContext context = null;

    //初始化
    public static void init(Context context){
        NIMClient.init(context, loginInfo(context), options());
        if (NIMUtil.isMainProcess(context)) {
            // 注意：以下操作必须在主进程中进行
            // 1、UI相关初始化操作
            // 2、相关Service调用
            onMessage();
            onLogout();
        }
    }

    //被踢出
    public static void onLogout(){
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode>() {
                    public void onEvent(StatusCode code) {
                        if (code.wontAutoLogin()) {
                            // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                            if(context != null){
                                context
                                        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                                        .emit("onLogout", null);
                            }
                            MyReactDelegate.isLogin = false;
                            MyReactDelegate.account = "";
                        }
                    }
                }, true);
    }

    //收到消息
    public static void onMessage(){
        Observer<List<IMMessage>> incomingMessageObserver =
                new Observer<List<IMMessage>>() {
                    @Override
                    public void onEvent(List<IMMessage> messages) {
                        // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
                        WritableArray chatLogList = Util.extratMessage(messages);
                        context
                                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                                .emit("onMessage", chatLogList);
                    }
                };
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);
    }

    // 如果返回值为 null，则全部使用默认参数。
    private static SDKOptions options() {
        SDKOptions options = new SDKOptions();
        options.asyncInitSDK = true;
        return options;
    }


    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    private static LoginInfo loginInfo(Context context) {
        SharedPreferences neteaseSettings = context.getSharedPreferences("netease", 0);
        String account = neteaseSettings.getString("account","");
        String token = neteaseSettings.getString("token","");
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }

    //解析消息
    public static WritableArray extratMessage(List<IMMessage> messageList){
        WritableArray chatLogList = new WritableNativeArray();
        for( int i = 0 ; i < messageList.size() ; i++) {//内部不锁定，效率最高，但在多线程要考虑并发操作的问题。
            if(messageList.get(i).getMsgType() == MsgTypeEnum.text) {
                WritableMap chatLog = new WritableNativeMap();
                //好友用户ID
                String uid = messageList.get(i).getFromAccount();
                if (uid == "911") continue;
                chatLog.putString("uid", uid);
                String content = messageList.get(i).getContent();
                chatLog.putString("content", content);
                Long time = messageList.get(i).getTime();
                chatLog.putString("time", String.valueOf(time));
                chatLogList.pushMap(chatLog);
            }
        }
        return chatLogList;
    }
}
